<template>
  <div class="employee-management">
    <el-card class="shadow-md rounded-lg p-5">
      <template #header>
        <div class="card-header flex justify-between items-center mb-4">
          <h2 class="text-xl font-bold text-gray-800">员工管理</h2>
          <el-button 
            type="primary" 
            @click="openEmployeeDialog()"
            class="bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-300 flex items-center px-4 py-2">
            <el-icon><Plus /></el-icon>
            <span>新增员工</span>
          </el-button>
        </div>
      </template>

      <el-table 
        :data="employeeList" 
        border 
        stripe
        highlight-current-row
        style="width: 100%"
        class="rounded-lg overflow-hidden mb-4">
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="employeeName" label="员工姓名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
        <el-table-column prop="position" label="职位" align="center"></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="openEmployeeDialog(scope.row)"
              class="bg-primary hover:bg-primary/90 text-white rounded transition-all duration-300 px-3 py-1">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteEmployee(scope.row)"
              class="bg-danger hover:bg-danger/90 text-white rounded transition-all duration-300 px-3 py-1">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex flex-col md:flex-row justify-between items-center mt-4 gap-4">
        <div class="text-sm text-gray-500">
          共 {{ total }} 条记录
        </div>
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          class="pagination w-full md:w-auto"
        ></el-pagination>
      </div>
    </el-card>

   <!-- 员工编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑员工' : '新增员工'" width="50%">
      <el-form :model="employeeForm" label-width="100px">
        <el-form-item label="员工姓名">
          <el-input v-model="employeeForm.employeeName" placeholder="请输入员工姓名"></el-input>
        </el-form-item>

        <el-form-item label="手机号码">
          <el-input v-model="employeeForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="employeeForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="职位">
          <el-input v-model="employeeForm.position" placeholder="请输入职位"></el-input>
        </el-form-item>

        <el-form-item label="密码" v-if="!isEdit">
          <el-input
            v-model="employeeForm.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEmployee">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { listEmployee, getEmployee, addEmployee, updateEmployee, delEmployee } from '@/api/employee'

// 引用表单进行验证
const formRef = ref(null)

// 员工列表
const employeeList = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框显示状态
const dialogVisible = ref(false)

// 是否为编辑模式
const isEdit = ref(false)

// 员工表单
const employeeForm = reactive({
  id: null,
  employeeName: '',
  phone: '',
  email: '',
  position: '',
  password: '',
})

// 获取员工列表
const getEmployeeList = async (params = {}) => {
  try {
    const res = await listEmployee({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...params
    })
    employeeList.value = res.data || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取员工列表失败', error)
    ElMessage.error('获取员工列表失败')
  }
}

// 打开员工对话框
const openEmployeeDialog = (employee) => {
  if (employee) {
    // 编辑模式
    isEdit.value = true
    Object.assign(employeeForm, employee)
  } else {
    // 新增模式
    isEdit.value = false
    // 重置表单
    Object.assign(employeeForm, {
      id: null,
      employeeName: '',
      phone: '',
      email: '',
      position: '',
      password: '',
    })
  }

  dialogVisible.value = true
  
  // 重置表单验证状态
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 验证并保存员工
const validateAndSave = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      saveEmployee()
    } else {
      return false
    }
  })
}

// 保存员工
const saveEmployee = async () => {
  try {
    if (isEdit.value) {
      // 编辑员工
      await updateEmployee(employeeForm)
      ElMessage.success('员工更新成功')
    } else {
      // 新增员工
      await addEmployee(employeeForm)
      ElMessage.success('员工添加成功')
    }

    // 关闭对话框
    dialogVisible.value = false

    // 刷新员工列表
    getEmployeeList()
  } catch (error) {
    console.error('保存员工失败', error)
    ElMessage.error(error.message || '保存员工失败')
  }
}

// 删除员工
const deleteEmployee = (employee) => {
  ElMessageBox.confirm(`确定要删除员工 ${employee.employeeName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await delEmployee(employee.id)
        ElMessage.success('员工删除成功')
        getEmployeeList()
      } catch (error) {
        console.error('删除员工失败', error)
        ElMessage.error(error.message || '删除员工失败')
      }
    })
    .catch(() => {})
}

// 页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  getEmployeeList()
}

// 每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getEmployeeList()
}

// 初始化
onMounted(() => {
  getEmployeeList()
})
</script>

<style scoped>
/* 基础样式变量 */
:root {
  --primary: #409eff;
  --success: #67c23a;
  --warning: #e6a23c;
  --danger: #f56c6c;
  --info: #909399;
  --bg-light: #f5f7fa;
  --text-primary: #303133;
  --text-secondary: #606266;
  --text-placeholder: #909399;
  --border-color: #dcdfe6;
  --border-radius: 8px;
  --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 工具类 */
.flex { display: flex; }
.justify-between { justify-content: space-between; }
.items-center { align-items: center; }
.rounded-lg { border-radius: var(--border-radius); }
.shadow-md { box-shadow: var(--box-shadow); }
.mb-4 { margin-bottom: 16px; }
.mb-5 { margin-bottom: 20px; }
.p-4 { padding: 16px; }
.p-5 { padding: 20px; }
.gap-4 { gap: 16px; }
.text-xl { font-size: 20px; }
.font-bold { font-weight: 600; }
.text-gray-800 { color: var(--text-primary); }
.text-gray-500 { color: var(--text-secondary); }
.bg-gray-50 { background-color: var(--bg-light); }
.w-64 { width: 256px; }

/* 卡片样式 */
.shadow-md {
  box-shadow: var(--box-shadow);
}

/* 表格样式 */
.rounded-lg {
  border-radius: var(--border-radius);
}

/* 分页样式 */
.pagination {
  margin-top: 0;
}

/* 对话框样式 */
.dialog-shadow {
  box-shadow: var(--box-shadow);
  border-radius: var(--border-radius);
  z-index: 2000;
}

/* 按钮过渡效果 */
button {
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .employee-management {
    padding: 10px;
  }
  
  .el-card {
    padding: 15px;
  }
  
  .el-table-column {
    min-width: auto !important;
  }
  
  .el-pagination {
    white-space: normal;
  }
  
  .dialog-shadow {
    width: 90%;
  }
  
  .search-area .el-form-item {
    margin-bottom: 10px;
  }
}
</style>